// m

// 给定一个整数数组nums和一个目标值target，要求从nums中选出三个整数，使它们的和与target最接近，返回这三个数的和，假定每组输入只存在恰好一个解

// 时间复杂度为O(n^2)
function threeSumClosest(nums, target) {
    // 进行升序排序
    nums.sort((a, b) => a - b)
    let size = nums.length
    let res = Number.MAX_SAFE_INTEGER
    for (let i = 2; i < size; i++) {
        let left = 0
        let right = i - 1 
        while (left < right) {
            let total = nums[left] + nums[right] + nums[i]
            if (Math.abs(total - target) < Math.abs(res - target)) {
                res = total
            }
            if (total < target) {
                left += 1
            } else {
                right -= 1
            }
        }
    }
    return res
}

let nums = [-1,2,1,-4], target = 1
console.log(threeSumClosest(nums, target))